package com.lanqiao.guimei.filter;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author stone(huangshizhang) at 2019-08-12 15:58
 */
public class SecureFilter extends HttpServlet implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 过滤操作，过滤用户请求
     *
     * @param servletRequest
     * @param servletResponse
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        HttpSession session = request.getSession();
        if (session.getAttribute("user") != null){
            chain.doFilter(request, response);
        } else {
            if (StringUtils.endsWith(request.getRequestURI(), "userLogin.do")){
                chain.doFilter(request, response);
            } else {
                response.sendRedirect(request.getContextPath() + "/index.jsp?noLog=0");
            }
        }
    }
}
